package com.qf.compusdemo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(".............");
//        Object token = request.getSession().getAttribute("token");
        Cookie[] cookies = request.getCookies();
        String cookieToken = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //如果找到存储自动登录cookie的名字就读取存储的账号和密码
                if (cookie.getName().equals("myshop-token")) {
                    cookieToken = cookie.getValue();
                }
            }
        }
        System.out.println("cookieToken:"+cookieToken);
        String sesseionToken = (String) request.getSession().getAttribute("token");
        System.out.println("sesseionToken:"+sesseionToken);
        if(sesseionToken!=null && sesseionToken.equals(cookieToken)){
            return true;
        }else {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().append("{\"code\":1,\"msg\":\"访问失败!token无效\",\"data\":\"failed\"}");
            return false;
        }

    }
}
